<template>
  <div>
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane v-for="(item, index) in list" :label="item.title" :key="index" :name="String(item.planMapId)">
        <el-button type="primary" size="mini" @click="addRoom">添加房间</el-button>
      </el-tab-pane>
    </el-tabs>

    <div id="myCanvas" :style="{ 'background-image': `url(${baseUrl + list[activeName - 1].url})` }">
      <canvas id="myCanvas" ref="myCanvas" @click="findRect" width="1500" height="1100" @mousedown="mousedown"
        @mouseup="mouseup" @mousemove="mousemove"></canvas>
    </div>

    <el-dialog title="房间信息" :visible.sync="canvasVisible" width="40%">
      <div v-if="totalRect.length > 0">
        <!-- {{ totalRect }} -->
        <div>房间号码：{{ totalRect[delIndex].code }}</div>
        <div style="margin-top: 10px;">房间名称：{{ totalRect[delIndex].name }}</div>
        <div style="margin-top: 10px;">
          描述：{{
            totalRect[delIndex].description
          }}
        </div>
        <el-image class="mt10" style="width: 100%; height: 100%" :src="baseUrl + totalRect[delIndex].roomUrl"></el-image>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="warning" @click="delRoom">删除</el-button>
        <el-button type="danger" @click="changeRoom(totalRect[delIndex])">设置设备点</el-button>
        <el-button type="danger" @click="onRightClick(totalRect[delIndex])">编辑</el-button>
        <el-button @click="canvasVisible = false">取 消</el-button>
      </span>
    </el-dialog>

    <el-dialog title="房间信息 " :visible.sync="dialogVisible" width="30%">
      <el-form ref="elForm" :model="formData" :rules="rules" size="medium" label-width="130px">
        <el-form-item label="房间号码" prop="code">
          <el-input v-model="formData.code" placeholder="请输入房间号码" clearable :style="{ width: '100%' }"></el-input>
        </el-form-item>
        <el-form-item label="房间名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入房间名称" clearable :style="{ width: '100%' }"></el-input>
        </el-form-item>
        <el-form-item label="房间描述" prop="description">
          <el-input v-model="formData.description" placeholder="请输入房间描述" clearable :style="{ width: '100%' }"></el-input>
        </el-form-item>
        <el-form-item label="房间照片" prop="roomUrl">
          <FileUpload :limit="1" :fileType="fileType" v-model="formData.roomUrl"></FileUpload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer" v-if="addShow">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitUserData">标记房间位置</el-button>
      </span>
      <span slot="footer" class="dialog-footer" v-else>
        <el-button type="primary" @click="editRoom">修改</el-button>
      </span>
    </el-dialog>
    <el-dialog :title="roomTitle" :visible.sync="roomShow" width="80%">
      <onlyequipMent placeholder="请选择设备" @change="changeCultivate" v-model="formData.cultivateUserId"></onlyequipMent>
      <div style="width: 100%;height: 100%;display: flex;align-items: center;">
        <img :src="roomImg" alt style="width: 100%;height: 100%;" @click="eqImgChange" />
        <el-tooltip placement="top" v-for="(point, index) in pointsRoom" :key="index">
          <div slot="content">
            <div>设备编号：{{ point.deviceCode }}</div>
            <div style="margin-top: 10px;">设备名称：{{ point.deviceName }}</div>
          </div>
          <div :style="{ top: `${point.deviceOrdinate}px`, left: `${point.deviceAbscissa}px` }" class="pointImg"
            @click="handleDetail(point)" @contextmenu.prevent="onRightClickEQ(point)"></div>
        </el-tooltip>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  planMapList,
  roomMapAdd,
  roomMapList,
  deviceMapList,
  deviceMapAdd,
  roomMapDel,
  roomMapEdit,
  deviceMappDel
} from "@/api/business/laboratory.js";
import onlyequipMent from "@/components/onlyequipMent";
let _time = null
export default {
  components: {
    onlyequipMent
  },
  data() {
    return {
      addShow: true,
      fileType: ["png", "jpge", "jpg"],
      rules: {
        code: [
          {
            required: true,
            message: "请输入房间编号",
            trigger: "blur"
          }
        ],
        name: [
          {
            required: true,
            message: "请输入房间名称",
            trigger: "blur"
          }
        ],
        roomUrl: [
          {
            required: true,
            message: "请上传房间照片",
            trigger: "blur"
          }
        ],
        description: [
          {
            required: false,
            message: "请输入房间描述",
            trigger: "blur"
          }
        ]
      },
      roomShow: false,
      activeName: "1",
      roomTitle: "",
      roomImg: "",
      pointsRoom: [],
      points: [
        // { x: 250, y: 190, index: 1 },
        // { x: 350, y: 205, index: 2 },
        // { x: 450, y: 215, index: 3 },
        // { x: 650, y: 240, index: 4 },
        // { x: 294, y: 294, index: 5 }
      ],
      formData: {},
      dialogVisible: false,
      baseUrl: this.$VUE_APP_IMG_API,
      list: [
        {
          url: ""
        }
      ],
      marks: [], // 存储标记点的位置，格式为{ x: 0.5, y: 0.5 }，其中0.5表示位于图片宽度和高度的50%
      startX: 0,
      startY: 0,
      startWidth: 0,
      startHeight: 0,
      scaleX: 1,
      scaleY: 1,
      pointShow: false,
      dataForm: {},
      roomMapId: "",
      flag: false,
      rectWidth: 0, //矩形框的宽
      rectHeight: 0, //矩形框的高
      totalRect: [], //画的所有的矩形坐标长度数据存储在数组中
      downX: 0, //鼠标点击图片落下时的位置（X）
      downY: 0, //鼠标点击图片落下时的位置（Y）
      ctx: "", //dom节点
      canvas: null,
      rectTag: false,
      delIndex: 0, //删除时选中的矩形框的index
      atime: null,
      dialogVisible: false, //删除的弹出框
      canvasVisible: false,

    };
  },
  computed: {
    imageStyle() {
      return {
        // 根据marks重新计算图片的transform样式
        transform: `scale(${this.scaleX}, ${this.scaleY})`
      };
    }
  },
  mounted() {
    this.planMapList();
    this.canvas = this.$refs.myCanvas;
    this.ctx = this.canvas.getContext("2d");
  },
  created() { },
  methods: {
    cumputNum(x, y, w, h, x1, y1,) {
      // x1 y1 :鼠标的位置，后面4个点 从左上角逆时针的坐标
      return this.isPointInsideRectangle(x1, y1, x, y, x, y + h, x + w, y + h, x + w, y)
    },
    crossProduct(ax, ay, bx, by) {
      return ax * by - ay * bx;
    },
    isPointInsideRectangle(x, y, x1, y1, x2, y2, x3, y3, x4, y4) {
      console.log(x, y, x1, y1, x2, y2, x3, y3, x4, y4);
      const d1 = this.crossProduct(x - x1, y - y1, x2 - x1, y2 - y1);
      const d2 = this.crossProduct(x - x2, y - y2, x3 - x2, y3 - y2);
      const d3 = this.crossProduct(x - x3, y - y3, x4 - x3, y4 - y3);
      const d4 = this.crossProduct(x - x4, y - y4, x1 - x4, y1 - y4);
      console.log(d1, d2, d3, d4);
      if ((d1 >= 0 && d2 >= 0 && d3 >= 0 && d4 >= 0) || (d1 <= 0 && d2 <= 0 && d3 <= 0 && d4 <= 0)) {
        return true;
      } else {
        return false;
      }
    },
    // 使用示例
    // 放下鼠标
    mousedown(e) {
      console.log("鼠标落下");
      this.atime = new Date().getTime();
      this.flag = true;
      this.downX = e.offsetX; // 鼠标落下时的X
      this.downY = e.offsetY; // 鼠标落下时的Y
      if (!this.pointShow) return;
      this.mousemove(e);
    },
    // 移动鼠标
    mousemove(e) {
      if(_time){
        clearTimeout(_time)
      }
      _time =   setTimeout(() =>{
        console.log("移动结束开始循环")
       let currentInfo = this.points.find(item => {
        let {
            beforex,
            beforey,
            rectW,
            rectH
          } = JSON.parse(item.abscissa)
          let flag = this.cumputNum(beforex, beforey, rectW, rectH, e.offsetX, e.offsetY)
          return flag
       })
       if(currentInfo){
        let _e = JSON.parse(currentInfo.abscissa)
         this.totalRect = [{
            beforex: _e.beforex,
            beforey: _e.beforey,
            rectW: _e.rectW,
            rectH: _e.rectH,
            code: currentInfo.code,
            description: currentInfo.description,
            name: currentInfo.name,
            ordinate:currentInfo.ordinate,
            planMapId:currentInfo.planMapId,
            roomMapId: currentInfo.roomMapId,
            roomUrl: currentInfo.roomUrl,
          }]
          // this.clear(); //清空画布
          this.redrawAll(); //重绘所有点
        }else{
          this.totalRect = []
          this.clear(); //清空画布
        }
      },300)
      if (this.flag) {
        //判断如果重右下往左上画，这种画法直接return
        if (!this.pointShow) return;
        if (this.downX - e.offsetX > 0 || this.downY - e.offsetY > 0) {
          return;
        } else {
          //如果重左上往右下画，计算出鼠标移动的距离，也就是矩形框的宽和高
          this.rectWidth = Math.abs(this.downX - e.offsetX);
          this.rectHeight = Math.abs(this.downY - e.offsetY);
          //判断这个宽高的长度，如果小于10，直接return，因为鼠标移动距离过于短
          //防止点击页面时,会画成一个点，没有意义
          if (this.rectWidth < 10 || this.rectHeight < 10) {
            this.rectWidth = 0;
            this.rectHeight = 0;
            return;
          }
          this.clear(); //清空画布
          this.redrawAll();
          this.drawRect(
            this.downX,
            this.downY,
            this.rectWidth,
            this.rectHeight
          );
        }
      }
    },
    // 抬起鼠标
    mouseup(e) {
      // console.log("鼠标抬起");
      this.flag = false;
      let a = new Date().getTime();
      if (a - this.atime > 150) {
        this.rectTag = false;
      } else {
        this.rectTag = true;
      }
      if (!this.pointShow) return;
      if (this.rectWidth || this.rectHeight) {
        //将画出的数据保存在totalRect中
        let rectItem = {
          beforex: this.downX,
          beforey: this.downY,
          rectW: this.rectWidth,
          rectH: this.rectHeight
        };
        this.totalRect.push(rectItem);
        this.addAnnotation(rectItem);
        console.log(this.totalRect);
      }
    },
    redrawAll() {
      console.log(this.totalRect,'有值？？');
      //    console.log("先画之前画过的图，保证画多个的时候看起来像前一个不消失");
      if (this.totalRect.length > 0) {
        this.drawRect(this.totalRect[0].beforex, this.totalRect[0].beforey, this.totalRect[0].rectW, this.totalRect[0].rectH);

        // this.totalRect.forEach(e => {
        //   //    console.log("eeeeeeeeeeeeeeeee",e);
        //   this.drawRect(e.beforex, e.beforey, e.rectW, e.rectH);
        // });
      }
    },
    //清除画布
    clear() {
      this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
    },
    drawRect(x, y, lineW, lineY) {
      console.log('开始绘制');

      //   开始绘制;
      this.ctx.beginPath();
      //   //设置线条颜色，必须放在绘制之前
      this.ctx.strokeStyle = "#409EFF";
      this.ctx.fillStyle = "rgba(64, 158, 255, 0.5)";
      //   // 线宽设置，必须放在绘制之前
      this.ctx.lineWidth = 2;
      // strokeRect参数：（左上角x坐标，y:左上角y坐标，绘画矩形的宽度，绘画矩形的高度）
      this.ctx.fillRect(x, y, lineW, lineY); //绘制填充矩形

    },
    //点击画布
    findRect(e) {
      console.log(this.rectTag, e,this.totalRect);
      if (this.rectTag) {
        console.log("eeeeeeeeeee", e);
        console.log("this.totalRect", this.totalRect);
        //当点击画布的时候，计算有没有点再矩形框内、哪个矩形框内
        this.totalRect.map((item, index) => {
          if (
            e.offsetX - item.beforex > item.rectW ||
            e.offsetX < item.beforex ||
            e.offsetY - item.beforey > item.rectH ||
            e.offsetY < item.beforey
          ) {
            return;
          } else {
            //找到之后，设置下标
            this.delIndex = index;
            console.log(this.totalRect[index]);
            //打开删除弹框
            this.canvasVisible = true;

            console.log("this.delIndex", this.delIndex);
          }
        });
      }
    },

    // 房间列表标记点
    roomMapList() {
      roomMapList({ planMapId: this.activeName }).then(res => {
        if (res.code == 200) {
          this.points = res.data;
          console.log(res.data);
          this.totalRect = [];
          // res.data.forEach(v => {
          //   this.totalRect.push({
          //     ...v,
          //     ...JSON.parse(v.abscissa)
          //   });
          // });
          // this.redrawAll();
        }
      });
    },
    // 设备列表标记点
    deviceMapList(e) {
      deviceMapList({ roomMapId: e }).then(res => {
        if (res.code == 200) {
          this.pointsRoom = res.data;
        }
      });
    },
    addRoom() {
      this.addShow = true;
      this.dialogVisible = true;
      this.formData = {
        code: "",
        name: "",
        description: "",
        roomUrl: ""
      };
    },
    changeRoom(e) {
      console.log(e);
      this.roomShow = true;
      this.roomTitle = e.name;
      this.roomImg = this.baseUrl + e.roomUrl;
      this.roomMapId = e.roomMapId;
      this.deviceMapList(e.roomMapId);
    },
    delChange() { },
    planMapList() {
      planMapList().then(res => {
        if (res.code == 200) {
          this.list = res.data;
          this.roomMapList();
        }
      });
    },
    submitUserData() {
      this.$refs["elForm"].validate(valid => {
        if (valid) {
          this.dialogVisible = false;
          this.pointShow = true;
          this.$message.warning("请在图片上标记出此房间得位置！");
        }
      });
    },
    handleDetail(row) {
      // "../equipmentInfoCard?isInfo=true&id=" + row.deviceId
      this.$router.push("./laboratoryInfo?isInfo=true&id=" + row.deviceId);
    },
    // 添加房间标记点
    addAnnotation(rectItem) {
      if (this.pointShow) {
        this.formData.planMapId = this.activeName;
        this.formData.abscissa = JSON.stringify(rectItem);
        // this.formData.ordinate = event.layerY;
        this.points.push(this.formData);
        roomMapAdd(this.formData).then(res => {
          if (res.code == 200) {
            this.$message.success("添加成功");
            this.pointShow = false;
            this.roomMapList();
          }
        });
      }
    },
    // 添加设备标记点
    eqImgChange(event) {
      if (this.eqRoomShow) {
        const obj = {
          deviceId: this.dataForm.deviceId,
          deviceCode: this.dataForm.deviceCode,
          roomMapId: this.roomMapId,
          deviceAbscissa: event.layerX,
          deviceOrdinate: event.layerY
        };
        this.pointsRoom.push(obj);
        deviceMapAdd(obj).then(res => {
          if (res.code == 200) {
            this.$message.success("添加成功");
            this.eqRoomShow = false;
            this.deviceMapList(this.roomMapId);
            // this.alBindList()
            // this.countByType()
          }
        });
      }
    },
    handleClick(tab, event) {
      this.totalRect = [];
      this.clear(); //清空画布
      this.roomMapList();
    },

    del() {
      //删除
      this.ctx.clearRect(
        this.totalRect[this.delIndex].beforex - 2,
        this.totalRect[this.delIndex].beforey - 2,
        this.totalRect[this.delIndex].rectW + 4,
        this.totalRect[this.delIndex].rectH + 4
      );
      //删掉totalRect的数据，真正的项目中需要调用后台接口，删掉数据库中存储的数据
      this.totalRect.splice(this.delIndex, 1);
      //删掉之后，再画一次，刷新页面
      this.redrawAll();
    },
    delRoom() {
      this.$confirm("此操作将永久删除该房间, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          let RoomMapIds = [];
          RoomMapIds.push(this.totalRect[this.delIndex].roomMapId);
          roomMapDel(RoomMapIds).then(res => {
            if (res.code == 200) {
              this.$message.success("删除成功");
              this.roomMapList();
              this.canvasVisible = false;
              this.addShow = true; //区分是添加房间还是修改
              this.del();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    editRoom() {
      this.$confirm("确定要修改此房间信息吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          roomMapEdit(this.formData).then(res => {
            if (res.code == 200) {
              this.$message.success("修改成功");
              this.roomMapList();
              this.dialogVisible = false;
              this.addShow = true; //区分是添加房间还是修改
            }
          });
        })
        .catch(() => {
          // this.$message({
          //     type: 'info',
          //     message: '已取消修改'
          // });
        });
    },
    // 房间右击
    onRightClick(e) {
      this.dialogVisible = true;
      this.addShow = false;
      this.formData = e;
    },
    // 设备右击
    onRightClickEQ(e) {
      console.log(e);
      this.$confirm("此操作将删除该设备，如需要请重新添加, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          let DeviceMapIds = [];
          DeviceMapIds.push(e.deviceMapId);
          deviceMappDel(DeviceMapIds).then(res => {
            if (res.code == 200) {
              this.$message.success("删除成功");
              this.deviceMapList(e.roomMapId);
              this.dialogVisible = false;
              this.addShow = true; //区分是添加房间还是修改
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    changeCultivate(e) {
      this.eqRoomShow = true;
      console.log(e);
      if (e) {
        this.dataForm = e;
        this.$message.warning("请在图片上标记出此设备得位置！");
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.pointImg {
  position: absolute;
  width: 10px;
  height: 10px;
  background-color: #ffd700;
  border-radius: 50%;
  cursor: pointer;
}

.test {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
}

#myCanvas {
  min-height: 1100px !important;
  //   background-image: url("../../../assets/images/yiceng.jpg");
  background-size: 1500px;
  background-repeat: no-repeat;
}

.dislog {
  width: 200px;
  height: 200px;
  background-color: pink;
  position: fixed;
  top: 30%;
  left: 50%;
  z-index: 999;
}
</style>